package com.xyht.sca_s.student_manage_system.modules.appDynamic.applicationDelivery;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.modules.appDynamic.applicationDelivery.req.AppConfirmAndResignReq;
import com.xyht.sca_s.student_manage_system.modules.appDynamic.applicationDelivery.req.AppJobChangeReq;
import com.xyht.sca_s.student_manage_system.modules.appDynamic.applicationDelivery.req.AppOnboardingApplicationReq;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsTeacherInfo;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsUserTeacherRelation;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsUserTeacherRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.appDynamic.applicationDelivery.AppConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.teacher.constant.ActiveStatusConstant.ACTIVE_STATUS_DEPART;
import static com.xyht.sca_s.student_manage_system.modules.teacher.constant.ActiveStatusConstant.ACTIVE_STATUS_WORK;
import static com.xyht.sca_s.student_manage_system.modules.teacher.constant.RoleConstant.ROLE_TEACHER;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.TeacherAndStudentFlag.TEACHER_FLAG;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.commonConstant.DEFAULT_PASSWORD;

/**
 * 应用接受type方法
 */
@Component
public class AppDelivery {

    @Resource
    private SmsUserTeacherRelationMapper userTeacherRelationMapper;
    @Resource
    private SmsTeacherInfoMapper teacherInfoMapper;
    @Resource
    private SmsOrgStructureMapper orgStructureMapper;
    @Resource
    private SmsOrgUserRelationMapper orgUserRelationMapper;
    @Resource
    private SmsUserMapper userMapper;
    @Resource
    private SmsUserRoleRelationMapper userRoleRelationMapper;

    @Transactional
    public boolean appDelivery(String reqStr,Integer type){

        //1.岗位变动
        if(type == APP_JOB_CHANGE){
            AppJobChangeReq jobChangeReq = JSON.parseObject(reqStr, AppJobChangeReq.class);
            if(isNullOrEmpty(jobChangeReq.getUserId(),jobChangeReq.getTchOrgId())){
                return false;
            }
            //组织id
            Integer orgId = Integer.parseInt(jobChangeReq.getTchOrgId());
            //用户id
            String userId = jobChangeReq.getUserId();
            //获取教师信息
            String tchId = getTeacherId(userId);
            SmsTeacherInfo teacherInfo = teacherInfoMapper.selectById(tchId);
            if(isNullOrEmpty(teacherInfo)){
                return false;
            }
            //组织信息
            SmsOrgStructure smsOrgStructure = orgStructureMapper.selectById(orgId);
            if(isNullOrEmpty(smsOrgStructure)){
                return false;
            }
            //修改教师的组织
            teacherInfo.setTchOrg(smsOrgStructure.getOrgName());//组织名
            teacherInfoMapper.updateById(teacherInfo);
            //修改用户和组织信息
            SmsOrgUserRelation orgUserRelation = new SmsOrgUserRelation();
            orgUserRelation.setOrgId(orgId.toString());
            LambdaQueryWrapper<SmsOrgUserRelation> orgUserQueryWrapper = new LambdaQueryWrapper<>();
            orgUserQueryWrapper.eq(SmsOrgUserRelation::getOrgId,orgId.toString())
                                .eq(SmsOrgUserRelation::getUserId,userId);
            orgUserRelationMapper.update(orgUserRelation,orgUserQueryWrapper);
        //2.新员工入职申请
        } else if (type == APP_ONBOARDING_APPLICATION) {
            AppOnboardingApplicationReq onboardingApplicationReq = JSON.parseObject(reqStr, AppOnboardingApplicationReq.class);
            if(isNullOrEmpty(onboardingApplicationReq.getTchName(),
                    onboardingApplicationReq.getTchSex(),onboardingApplicationReq.getTchIdCard())){
                return false;
            }

            //组织id
            Integer orgId = Integer.parseInt(onboardingApplicationReq.getTchOrg());
            //组织信息
            SmsOrgStructure smsOrgStructure = orgStructureMapper.selectById(orgId);
            if(isNullOrEmpty(smsOrgStructure)){
                return false;
            }

            //创建教师信息
            SmsTeacherInfo addTeacherInfo = new SmsTeacherInfo();
            BeanUtils.copyProperties(onboardingApplicationReq, addTeacherInfo);
            //工号与电话一致
            addTeacherInfo.setTchNo(onboardingApplicationReq.getTchTel());
            addTeacherInfo.setTchOrg(smsOrgStructure.getOrgName());
            addTeacherInfo.setIsAssistant("否");
            teacherInfoMapper.insert(addTeacherInfo);

            String tchId = addTeacherInfo.getId();

            //创建用户信息
            SmsUser addUser = new SmsUser();
            addUser.setFlag(TEACHER_FLAG);
            addUser.setPassword(DEFAULT_PASSWORD);
            addUser.setRealName(addTeacherInfo.getTchName());
            addUser.setUsername(addTeacherInfo.getTchNo());
            addUser.setTel(addTeacherInfo.getTchTel());
            userMapper.insert(addUser);

            String userId = addUser.getId();

            //创建教师和用户信息
            SmsUserTeacherRelation addUserTeacherRelation = new SmsUserTeacherRelation();
            addUserTeacherRelation.setUserId(userId);
            addUserTeacherRelation.setTchId(tchId);
            userTeacherRelationMapper.insert(addUserTeacherRelation);

            //创建用户与组织信息
            SmsOrgUserRelation addOrgUserRelation = new SmsOrgUserRelation();
            addOrgUserRelation.setUserId(userId);
            addOrgUserRelation.setOrgId(orgId.toString());
            orgUserRelationMapper.insert(addOrgUserRelation);

            //创建用户和角色的信息
            SmsUserRoleRelation addUserRoleRelation = new SmsUserRoleRelation();
            addUserRoleRelation.setUserId(userId);
            //教师
            addUserRoleRelation.setRoleId(ROLE_TEACHER);
            userRoleRelationMapper.insert(addUserRoleRelation);

        //3.转正申请
        } else if (type == APP_CONFIRMATION_APPLICATION) {
            return getConfirmAndResign(type, reqStr);
        //4.离职申请
        } else if (type == APP_RESIGNATION_APPLICATION) {
            return getConfirmAndResign(type, reqStr);
        }else {
            return false;
        }
        return true;
    }

    private String getTeacherId(String userId){
        List<SmsUserTeacherRelation> smsUserTeacherRelations = userTeacherRelationMapper.selectList(new LambdaQueryWrapper<SmsUserTeacherRelation>()
                .eq(SmsUserTeacherRelation::getUserId, userId));
        if(smsUserTeacherRelations == null || smsUserTeacherRelations.size() < 1){
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.TEACHER_NOT_EXIST));
        }
        SmsUserTeacherRelation userTeacherRelation = smsUserTeacherRelations.get(0);
        return userTeacherRelation.getTchId();
    }

    private boolean getConfirmAndResign(Integer type,String reqStr){
        AppConfirmAndResignReq confirmAndResignReq = JSON.parseObject(reqStr, AppConfirmAndResignReq.class);
        if(isNullOrEmpty(confirmAndResignReq.getUserId())){
            return false;
        }
        String userId = confirmAndResignReq.getUserId();
        String tchId = getTeacherId(userId);
        SmsTeacherInfo teacherInfo = teacherInfoMapper.selectById(tchId);
        if(isNullOrEmpty(teacherInfo)){
            return false;
        }
        //3.转正申请
        if(type == APP_CONFIRMATION_APPLICATION) {
            teacherInfo.setActiveStatus(ACTIVE_STATUS_WORK);
        //4.离职申请
        }else if(type == APP_RESIGNATION_APPLICATION){
            teacherInfo.setActiveStatus(ACTIVE_STATUS_DEPART);
        }
        teacherInfoMapper.updateById(teacherInfo);
        return true;
    }

}
